<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                  |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                   |
// +------------------------------------------------------------------------+
// | Author: liguohua@clcw.com.cn Blog:http://blog.sina.com.cn/saverneo     |
// +------------------------------------------------------------------------+
//
/**
 * 拍单管理
 */

namespace AuctionBack\Controller;

use AuctionCore\System\AuctionException;
use AuctionCore\AuctionOrder\Scene;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarList as CarList;
use AuctionCore\CarResource\CarSource;
use AuctionBack\Service\Thrift\ThriftAuctionService;
use Services\AuctionService\inParamsCreateOrder;

class CarController extends BaseController
{

    public $transfer_fee = 1000;
    public $commision = 1000;
    public $emp_id = 0;
    private $auctionServiceObj;

    public function __construct()
    {
        parent::__construct();

        //获取拍卖公共设置
        $auSetting = new \AuctionCore\AuctionOrder\AuctionSetting();
        try {
            if ($this->user_info['branch_id'] > 0) {
                $city_code = M('branch_city')->where("branch_id='" . $this->user_info['branch_id'] . "'")->getField('city_code');
                $transfer_fee = $auSetting->detail_by_name('TRANSFER_FEE_' . $city_code); //过户费
                $commision = $auSetting->detail_by_name('COMMISION_' . $city_code); //交易佣金
                $est_elapsed_time = $auSetting->detail_by_name('EST_ELAPSED_TIME_' . $city_code); //拍卖时长
            }
        } catch (AuctionException $e) {
            //die($e->getMessage());
        }
        $this->transfer_fee = $transfer_fee['value'];
        $this->commision = $commision['value'];
        $this->est_elapsed_time = $est_elapsed_time['value'];
        $this->emp_id = $this->user_info['emp_id'];
        $this->auctionServiceObj = new ThriftAuctionService();
    }

    public function index()
    {
        //场次下拉
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $map = array();
        if (!$this->is_hq) {
            $map['city'] = array('in', array_flip($this->bc_city));
        }
        $scenes = $scene->get_scenes($map);

        $scene = new Scene();
        $city = $scene->get_cicy_by_branch_id();

        //获取分公司
        $branch_company = $this->get_branch_company_list();
        $this->assign('city_code', $city['city_code']);
        $this->assign("scenes", $scenes);
        $this->assign("car_status", C("CAR_STATUS"));
        $this->assign("branch_company", $branch_company);
        $this->assign("transfer_fee", $this->transfer_fee);
        $this->assign("commision", $this->commision);
        $this->assign("est_elapsed_time", $this->est_elapsed_time);
        $this->display();
    }

    //获取车源的保留价.建议最低价，建议遇高价
    public function get_reserve_price()
    {
        $car_id = I('get.car_id');
        $car = new Car($car_id);
        $detail = $car->detail();
        $last_order_detail = \AuctionCore\AuctionOrder\AuOrder::get_order_by_car_id($car_id);
        $last_order_best_price = $last_order_detail['bidding_best_price'] > $last_order_detail['bid_best_price'] ?
            $last_order_detail['bidding_best_price'] : $last_order_detail['bid_best_price'];
        $price = array(
            'reserve_price' => $detail['reserve_price'],
            'reserve_price_cn' => format_money($detail['reserve_price']),
            'suggest_min_price' => $detail['suggest_min_price'],
            'suggest_min_price_cn' => format_money($detail['suggest_min_price']),
            'suggest_max_price' => $detail['suggest_max_price'],
            'suggest_max_price_cn' => format_money($detail['suggest_max_price']),
            'car_status' => $detail['car_status'],
            'last_order_best_price' => $last_order_best_price,
            'suggest_bid_start_price' => $detail['suggest_bid_start_price'],
        );
        $this->helpJsonResult(200, "", $price);
        exit;
    }

    //上拍车辆列表
    public function get_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['car_status'] = I("get.car_status");
        // $params['brand_id'] = I("get.brand_id");
        $params['series_id'] = I("get.series_id");
        $params['model_id'] = I("get.model_id");
        $params['keyword'] = I("get.keyword");
        $params['location_area'] = I('get.location_area');
        if (!$params['location_area']) {
            $params['location_area'] = !$this->is_hq ? array_flip($this->bc_city) : array();
        }
        //获取list
        $cl = new CarList();
        $result = $cl->get_list($page, $size, $params);
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出

        //模板赋值
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign("params", $params);
        $this->assign("transfer_fee", $this->transfer_fee);
        $this->assign("commision", $this->commision);
        /*if($params['car_status'] == 4 || $params['car_status'] == 7 || $params['car_status'] == 'all'){
            echo '454545';die;
        }*/

        if ($params['car_status'] == 2) {
            $this->display('audit_dismissed_list');

        } elseif ($params['car_status'] == 5) {

            $this->display('audit_pass_list');

        } elseif ($params['car_status'] === '0') {

            $this->display('fail_car_list');

        } elseif ($params['car_status'] == 4 || $params['car_status'] == 7 || $params['car_status'] == 'all') { //待上拍 和待重拍
            $this->display('car_list');
        }
        //echo $params['car_status'];
    }

    //新建拍单
    public function add_order()
    {
        //从表单获取数据
        $car_id = I('post.car_id');
        $scene_id = I('post.scene_id');
        $coupon = I('post.coupon');
        $bidding_start_time = I('post.bidding_start_time');
        $bid_start_price = I('post.bid_start_price');
        $est_elapsed_time = I('post.est_elapsed_time'); //竞拍时长
        $transfer_fee = I('post.transfer_fee'); //过户费
        $show_reserve_price = I('post.show_reserve_price');//是否显示保留价
        $suggest_min_price = I('post.suggest_min_price');
        $suggest_max_price = I('post.suggest_max_price');

        $parameters = new inParamsCreateOrder();
        $parameters->carId = intval($car_id);               //上拍车辆
        $parameters->sceneId = intval($scene_id);              //上拍场次
        $parameters->estElapsedTime = intval($est_elapsed_time * 60);        //竞拍时长
        $parameters->bidStartPrice = doubleval($bid_start_price);     //起拍价
        $parameters->transferFee = doubleval($transfer_fee);       //交付服务费
        $parameters->biddingStartTime = strtotime($bidding_start_time);     //竞拍开始时间
        $parameters->coupon = intval($coupon);               //代金券
        $parameters->showReservePrice = $show_reserve_price;    //是否显示保留价
        $parameters->empId = intval($this->user_info['emp_id']);               //上拍人
        $result = $this->auctionServiceObj->createOrder($parameters);
        if ($result === true) {
            $result = [
                'code' => 200,
                'msg' => '成功'
            ];
        }

        $this->helpJsonResult($result['code'], $result['msg']);
        return;

        /*//实例车源
        $car = new Car($car_id);
        $car_info = $car->detail();
        //验证定价是否有修改
        if ($car_info['suggest_min_price'] !== $suggest_min_price || $car_info['suggest_max_price'] !== $suggest_max_price) {
            $this->helpJsonResult('599', '定价已修改,请重新上拍');
        }
        //上拍要提前场开始时间2分钟
        $scene = new Scene();
        $scene_detail = $scene->detail($scene_id);
        //判断场次所属城市是否与车辆所在地相符
        if ($scene_detail['city'] != $car_info['location_area']) {
            $this->helpJsonResult('554', '场次所属城市与车辆所在地不符，请重新选择场次');
        }

        if ((time() + 120) > strtotime($scene_detail['starttime'])) {
            $this->helpJsonResult('554', '本场次已停止添加车辆，请安排到下一场次');
        }
        //如果是定时单需要判断指定的开拍时间是否合法
        if ($bidding_start_time) {
            $ret = $car->check_bidding_start_time($scene_id, $bidding_start_time);
            if (!$ret) {
                $this->helpJsonResult('549', '定时单开拍时间不能早于场次开始时间且必须和场次是同一天');
            }
        }
        //数据
        $data = array();
        //$data['emp_id'] = $this->emp_id;//新上拍这个字段为0，客服点点确认后
        //表单数据
        $data['car_id'] = $car_id; //车源ID
        $data['scene_id'] = $scene_id; //场次ID
        $data['est_elapsed_time'] = $est_elapsed_time * 60; //预计耗时
        if ($bidding_start_time) {
            $data['bidding_start_time'] = $bidding_start_time; //开拍时间
            $data['is_timing_order'] = '1'; //定时单
        } else {
            $data['bidding_start_time'] = $car->get_bidding_start_time($scene_id); //算出开拍时间
            $data['is_timing_order'] = '0'; //顺序单
        }
        $data['bid_start_price'] = $bid_start_price; //起拍价
        $data['coupon'] = $coupon; //可用代金券额度
        $data['transfer_fee'] = $transfer_fee; //过户费
        $data['commision'] = get_commision($bid_start_price, $scene_detail['starttime']); //交易服务费
        $data['reserve_price'] = $car_info['reserve_price'];
        $data['status'] = '1'; //1 审核中
        $data['show_reserve_price'] = $show_reserve_price;

        try {
            $order_id = $car->create_order($data);
            if (!$order_id) {
                $this->helpJsonResult(500, '上拍失败123456');
            }
        } catch (AuctionException $e) {
            $this->helpJsonResult($e->getCode(), $e->getMessage());
        }
        //更新车源拍单ID
        $CarSource = new CarSource($car_info['sid']);
        $CarSourceInfo = $CarSource->getInfo();
        $res_cs = true;
        if ($CarSourceInfo['status'] == 100) {
            $csData = [];
            $csData['order_id'] = $order_id;
            $res_cs = $CarSource->update($csData);
        }
        //记录车辆跟踪日志
        $car_action_data = array(
            'action_name' => '开始上拍',
            'emp_id' => $this->user_info['emp_id']
        );
        Car::add_car_trace_log($car_id, $car_action_data);
        //记录拍品跟踪日志 -- 开始
        $order_action_data = array(
            'action_name' => '开始上拍',
            'emp_id' => $this->user_info['emp_id']
        );
        AuOrder::add_order_trace_log($order_id, $order_action_data);
        $this->helpJsonResult(200, "拍单创建成功 ");*/
    }

    /**
     * 车源检测报告
     */
    public function report()
    {
        $car_id = I('get.car_id');
        //获取车辆检测报告
        $c = new Car($car_id);
        $car_info = $c->detail();

        $carIds = $c->getCarIdsBySid($car_info['sid']);
        $count = count($carIds);

        if (empty($car_info)) {
            $this->helpJsRedirect("未查询到车辆信息");
        }
        $procedure = $c->detail('car_procedure');
        //获取车辆检测报告
        $Rep = A('CarReport');
        $report = $Rep->output_report($car_info['car_id']);

        $this->assign('total_car', $count);
        $this->assign('car_id_list', $carIds);
        $this->assign('car_id', $car_id);
        $this->assign('report', $report);
        $this->assign('car', $car_info);
        $this->assign('procedure', $procedure);
        $this->display();
    }

    /**
     * 没有头部的检测报告
     */
    public function reportWithoutHeader()
    {
        $car_id = I('get.car_id');
        //获取车辆检测报告
        $c = new Car($car_id);
        $car_info = $c->detail();

        if (empty($car_info)) {
            $this->helpJsRedirect("未查询到车辆信息");
        }
        $procedure = $c->detail('car_procedure');
        //获取车辆检测报告
        $Rep = A('CarReport');
        $report = $Rep->output_report($car_info['car_id']);

        $this->assign('car_id', $car_id);
        $this->assign('report', $report);
        $this->assign('car', $car_info);
        $this->assign('procedure', $procedure);
        $this->display();
    }


    public function reportWithCert()
    {
        $car_id = I('get.car_id');
        //获取车辆检测报告
        $c = new Car($car_id);
        $car_info = $c->detail();
        if (empty($car_info)) {
            $this->helpJsRedirect("未查询到车辆信息");
        }
        $carIds = $c->getCarIdsBySid($car_info['sid']);
        $count = count($carIds);

        $car_info['transfer_limit'] = C('TRANSFER_LIMIT.' . $car_info['transfer_limit']);
        $car_info['suggest_price'] = format_money($car_info['suggest_min_price']) . "元 - " . format_money($car_info['suggest_max_price']);
        $car_info['reserve_price'] = format_money($car_info['reserve_price']);

        $procedure = $c->detail('car_procedure');
        $procedure['protocol_pic'] = get_content_cdnurl() . $procedure['protocol_pic'];
        $procedure['travel_license_pic'] = get_content_cdnurl() . $procedure['travel_license_pic'];
        $procedure['travel_license_pic2'] = get_content_cdnurl() . $procedure['travel_license_pic2'];
        $procedure['travel_license_pic3'] = get_content_cdnurl() . $procedure['travel_license_pic3'];
        $procedure['reg_cert_pic'] = get_content_cdnurl() . $procedure['reg_cert_pic'];
        $procedure['reg_cert_pic2'] = get_content_cdnurl() . $procedure['reg_cert_pic2'];
        $procedure['reg_cert_pic3'] = get_content_cdnurl() . $procedure['reg_cert_pic3'];
        //获取车辆检测报告
        $Rep = A('CarReport');
        $report = $Rep->output_report($car_info['car_id']);

        $this->assign('car_id', $car_id);
        $this->assign('total_car', $count);
        $this->assign('car_id_list', $carIds);
        $this->assign('report', $report);
        $this->assign('car', $car_info);
        $this->assign('procedure', $procedure);
        $this->display();
    }

    /**
     * 设置费用
     */
    public function set_fee()
    {

        $branch_id = I('post.branch_id');
        $city = M('branch_city')->where("branch_id='" . $branch_id . "'")->getField('city_code');

        //获取拍卖公共设置
        $auSetting = new \AuctionCore\AuctionOrder\AuctionSetting();
        $data = array();
        $data['value'] = I('post.commision');
        //设置交易佣金
        $cond = "name='COMMISION_" . $city . "'";
        $res1 = $auSetting->update($cond, $data);
        //设置交易佣金
        $data = array();
        $data['value'] = I('post.transfer_fee');
        $cond = "name='TRANSFER_FEE_" . $city . "'";
        $res2 = $auSetting->update($cond, $data);

        //设置拍卖时长
        $data = array();
        $data['value'] = I('post.est_elapsed_time');
        $cond = "name='EST_ELAPSED_TIME_" . $city . "'";
        $res3 = $auSetting->update($cond, $data);

        if ($res1 !== false && $res2 !== false && $res3 !== false) {
            $this->helpJsonResult(200, "设置成功");
        } else {
            $this->helpJsonResult(508, "设置失败");
        }
        exit;
    }

    /**
     * 报告失效
     */
    public function failureReport()
    {
        $car_id = I("post.car_id/d");
        if ($car_id < 1) {
            $this->helpJsonResult(400, "参数不正确");
        }
        $car = new Car($car_id);
        $carDetail = $car->detail();
        if (!in_array($carDetail['car_status'], [4, 5, 7])) {
            $this->helpJsonResult(400, "状态不正确");
        }
        $result = $car->update(['car_status' => 8, 'is_valid' => 0]);
        if (!$result) {
            $this->helpJsonResult(500, '操作失败');
        }
        //记录车辆跟踪日志
        $car_action_data = array(
            'action_name' => '报告失效',
            'emp_id' => $this->emp_id
        );
        Car::add_car_trace_log($car_id, $car_action_data);
        $this->helpJsonResult(200, '操作成功');
    }
}
